package com.hlk.interceptors;

import com.hlk.enums.ResponseStatusEnum;
import com.hlk.exception.HuaException;
import com.hlk.utils.redis.RedisKeys;
import com.hlk.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class BaseInterceptor {

    @Autowired
    private RedisUtils redisUtils;


    public boolean verifyUserIdToken(String userId, String token, String redisKey) {

        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(token)) {
            String redisToken = redisUtils.get(redisKey);
            if (StringUtils.isBlank(userId)) {
                throw new HuaException(ResponseStatusEnum.UN_LOGIN);
            } else {
                if (!redisToken.equalsIgnoreCase(token)) {
                    throw new HuaException(ResponseStatusEnum.TICKET_INVALID);
                }
            }
        } else {
            throw new HuaException(ResponseStatusEnum.UN_LOGIN);
        }

        return true;
    }

    // 从cookie中取值
    public String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                String value = cookie.getValue();
                return value;
            }
        }
        return null;
    }

}
